import { CALLBACK_AGGREGATE } from '../config';
import { logError } from '../util';

/**
 *回调函数集合
 *
 * @class CallbackAggregate
 */
export default class CallbackAggregate {
    static add = (CB_NAME, callBack, failCallBack) => {
        if (!window[CALLBACK_AGGREGATE]) {
            window[CALLBACK_AGGREGATE] = {};
        }
        window[CALLBACK_AGGREGATE][CB_NAME] = {
            cb: callBack,
            fcb: failCallBack,
        };
    };

    static remove = CB_NAME => {
        if (!window[CALLBACK_AGGREGATE]) {
            logError('请检查当前环境');
            return;
        }
        delete window[CALLBACK_AGGREGATE][CB_NAME];
    };

    static call = ({ CB_NAME, type, object = {} }) => {
        if (!window[CALLBACK_AGGREGATE]) {
            logError('请检查当前环境');
            return;
        }
        const callback = window[CALLBACK_AGGREGATE][CB_NAME];

        if (!callback) {
            logError(`回调函数不存在或已删除,${callback},${CB_NAME}`);
            return;
        }
        if (type === 1) {
            callback.fcb && callback.fcb(object || {});
        } else {
            callback.cb && callback.cb(object || {});
        }
    };
}
